#include "userregister.h"
#include "ui_userregister.h"
#include "RegisterLineEdit.hpp"
#include <QBuffer>

UserRegister::UserRegister(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserRegister)
  , m_avatarPixmap(":/image/default_avatar.png")
{
    ui->setupUi(this);
    setAttribute(Qt::WA_StyledBackground, true);

    QPixmap pixmap(":/image/close_window.png");
    ui->close_window->setIcon(pixmap);

    QRegularExpression re_for_username("^\\S*$");

    // 创建四个自定义的LineEdit
    username = new RegisterLineEdit(this);
    username->setGeometry(50, 120, 140, 30);
    username->setToolTip("只允许字母和数字，不允许空格");
    username->setPlaceholderText("请输入昵称");
    username->setValidator(new QRegularExpressionValidator(re_for_username, this));


    // 设置输入验证（仅允许字母和数字）
    QRegularExpression re("^[a-zA-Z0-9]+$");

    userid = new RegisterLineEdit(this);
    userid->setGeometry(50, 155, 140, 30);
    userid->setToolTip("只允许字母和数字");
    userid->setPlaceholderText("请输入账号");
    userid->setValidator(new QRegularExpressionValidator(re, userid));

    password = new RegisterLineEdit(this);
    password->setEchoMode(QLineEdit::EchoMode::Password);
    password->setGeometry(50, 190, 140, 30);
    password->setToolTip("只允许字母和数字，长度不小于8");
    password->setPlaceholderText("请输入密码");
    userid->setValidator(new QRegularExpressionValidator(re, password));

    password_conform = new RegisterLineEdit(this);
    password_conform->setGeometry(50, 225, 140, 30);
    password_conform->setEchoMode(QLineEdit::EchoMode::Password);
    password_conform->setPlaceholderText("确认密码");
    userid->setValidator(new QRegularExpressionValidator(re, password_conform));


    connect(password_conform, &QLineEdit::textChanged, this, [=](QString text)
    {
        (void)text;
        if(!username->text().isEmpty() && !userid->text().isEmpty() && password->text().length() >= 8 && password_conform->text() == password->text())
        {
            ui->pushButton->setEnabled(true);
        }
        else
        {
            ui->pushButton->setEnabled(false);
        }
    });
}

UserRegister::~UserRegister()
{
    delete ui;
}

void UserRegister::on_pushButton_2_clicked()
{
    emit goBack();
}

void UserRegister::on_close_window_clicked()
{
    emit closeWindow();
}

void UserRegister::paintEvent(QPaintEvent *event)
{
    (void)event;

   // 绘制圆形头像
   {
    // 直接在Widget上绘制
       QPainter painter(this);
       int x = 89, y = 39, w = 62, h = 62;
       QPainterPath path;
       path.addEllipse(x, y, w, h);
       painter.setClipPath(path);

       if (!m_avatarPixmap.isNull())
       {
           painter.drawPixmap(x + 1, y + 1, w - 2, h - 2, m_avatarPixmap);
       } else
       {
           // 处理加载失败的情况
           painter.fillRect(x + 1, y + 1, w - 2, h - 2, Qt::lightGray);
           painter.setClipPath(QPainterPath()); // 取消裁剪
           painter.drawText(x + 1, y + 1, w - 2, h - 2, Qt::AlignCenter, "!");
           return;
       }

       painter.setRenderHint(QPainter::Antialiasing); // 启用抗锯齿


       QPen pen; // 2像素宽的边框
       pen.setColor(Qt::black);
       pen.setWidth(2);
       painter.setPen(pen);
       painter.drawEllipse(x, y, w, h);
   }
}

void UserRegister::on_pushButton_3_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(
        this,
        tr("选择新头像"),
        "",
        tr("图像文件 (*.png *.jpg *.jpeg *.bmp)")
    );

    if (!fileName.isEmpty())
    {
        // 加载新选择的头像
        m_avatarPixmap = QPixmap(fileName);

        if (!m_avatarPixmap.isNull())
        {
            // 调整图像大小以适应圆形区域
            m_avatarPixmap = m_avatarPixmap.scaled(60, 60, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
            update(); // 触发重绘
        } else
        {
            qDebug() << "Failed to load selected image!";
        }
    }
}


void UserRegister::on_pushButton_clicked()
{
    QByteArray imageData;
    QBuffer buffer(&imageData);
    buffer.open(QIODevice::WriteOnly);
    m_avatarPixmap.save(&buffer, "PNG");

    // 2. 对二进制数据进行Base64编码
    QString head = QString::fromUtf8(imageData.toBase64());
//    qDebug() << "报文长度" << head.length();

    emit commit(username->text(), userid->text(), password->text(), head);
}
